﻿package cn.poco.pepsi.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashSet;

import android.content.Context;

public class DownloadImage {
	private File cacheDir;
	public static HashSet<String> uriSet = new HashSet<String>();

	public DownloadImage(Context mContext, int i) {
		cacheDir = mContext.getCacheDir();
	}

	public DownloadImage(Context mContext) {
		// 如果储存卡状态可以用，那么缓存的文件文件的文件根路径设置在存储卡
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "PocoFood");
			if (!cacheDir.exists()) {
				System.out.println("mkdir in sdcard result:" + cacheDir.mkdir());
			}
		} else {
			cacheDir = mContext.getCacheDir();
		}
	}

	/**
	 * 传入一个要load的路径，返回一个本地cacher地址
	 * @param 图片网址
	 * @return 本地Cacher地址
	 * @throws Exception
	 */
	public String download(String path) throws Exception {
		String myPath = null;
		File dFile = new File(cacheDir, MD5Utils.toMD5(path));
		if (dFile.exists()) {
			myPath = dFile.toString();
		} else {
			InputStream inStream = UrlConnectionUtil.getRequest(path);
			FileOutputStream outStream = new FileOutputStream(dFile, true);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer))>0) {
				outStream.write(buffer, 0, len);
			}
			inStream.close();
			outStream.close();
			myPath = dFile.toString();
		}
		return myPath;
	}

}
